package com.ai.chatapi.serviceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Open-AI ChatGPT
 *
 * @author houwenpeng
 */
@Service
public class AiService {

    private static final String url = "https://api.openai.com/v1/models";
    private static final String OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";

    @Value("${chat.api-key}")
    private String OPENAI_API_KEY;

    public String getAiResponse(String prompt) throws Exception {

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Authorization", "Bearer " + OPENAI_API_KEY);

            HttpEntity responseEntity = client.execute(httpGet).getEntity();
            String response = EntityUtils.toString(responseEntity);

            System.out.println("当前key可使用的模型:"+response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(OPENAI_API_URL);

        // 设置 API 密钥和请求头
        httpPost.setHeader("Authorization", "Bearer " + OPENAI_API_KEY);
        httpPost.setHeader("Content-Type", "application/json");

        // 创建请求体
        JSONObject json = new JSONObject();
        json.put("model", "gpt-3.5-turbo");  // 使用 GPT-3.5-turbo 模型
        json.put("messages", new JSONArray().put(new JSONObject().put("role", "user").put("content", prompt)));
        json.put("max_tokens", 100);

        // 将请求体设置为 POST 请求的实体
        StringEntity entity = new StringEntity(json.toString());
        httpPost.setEntity(entity);

        // 执行请求并获取响应
        HttpEntity responseEntity = client.execute(httpPost).getEntity();
        String response = EntityUtils.toString(responseEntity);

        // 解析返回的 JSON 内容并提取模型的回复
        JSONObject responseJson = new JSONObject(response);
        return responseJson.getJSONArray("choices").getJSONObject(0).getString("message").trim();
    }

}
